// 日志级别枚举
export enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3
}

// 日志条目接口
interface LogEntry {
  level: LogLevel;
  message: string;
  timestamp: Date;
  data?: any;
}

class Logger {
  private minLevel: LogLevel;
  private logs: LogEntry[] = [];

  constructor(minLevel: LogLevel = LogLevel.INFO) {
    this.minLevel = minLevel;
  }

  // 设置最小日志级别
  setMinLevel(level: LogLevel): void {
    this.minLevel = level;
  }

  // 记录日志的通用方法
  private log(level: LogLevel, message: string, data?: any): void {
    // 在生产环境中忽略 DEBUG 和 INFO 级别的日志
    if (process.env.NODE_ENV === 'production' && level < LogLevel.WARN) {
      return;
    }

    // 只记录等于或高于最小级别的日志
    if (level >= this.minLevel) {
      const logEntry: LogEntry = {
        level,
        message,
        timestamp: new Date(),
        data
      };

      this.logs.push(logEntry);

      // 在开发环境中输出到控制台
      if (process.env.NODE_ENV !== 'production') {
        switch (level) {
          case LogLevel.DEBUG:
            console.debug(`[DEBUG] ${message}`, data || '');
            break;
          case LogLevel.INFO:
            console.info(`[INFO] ${message}`, data || '');
            break;
          case LogLevel.WARN:
            console.warn(`[WARN] ${message}`, data || '');
            break;
          case LogLevel.ERROR:
            console.error(`[ERROR] ${message}`, data || '');
            break;
        }
      }
    }
  }

  // DEBUG 级别日志
  debug(message: string, data?: any): void {
    this.log(LogLevel.DEBUG, message, data);
  }

  // INFO 级别日志
  info(message: string, data?: any): void {
    this.log(LogLevel.INFO, message, data);
  }

  // WARN 级别日志
  warn(message: string, data?: any): void {
    this.log(LogLevel.WARN, message, data);
  }

  // ERROR 级别日志
  error(message: string, data?: any): void {
    this.log(LogLevel.ERROR, message, data);
  }

  // 获取所有日志
  getLogs(): LogEntry[] {
    return [...this.logs];
  }

  // 清空日志
  clearLogs(): void {
    this.logs = [];
  }

  // 导出日志为文本格式
  exportLogs(): string {
    return this.logs.map(log => {
      const levelStr = LogLevel[log.level];
      const timestampStr = log.timestamp.toISOString();
      const dataStr = log.data ? JSON.stringify(log.data) : '';
      return `[${timestampStr}] ${levelStr}: ${log.message} ${dataStr}`;
    }).join('\n');
  }
}

// 创建并导出默认的日志实例
const logger = new Logger(process.env.NODE_ENV === 'production' ? LogLevel.WARN : LogLevel.DEBUG);

export default logger;